package com.zt.reggie.controller;

import com.zt.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec com.zt.reggie.controller
 * @since 2023 - 02 - 26 - 9:29
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){    //参数名和前端保持一致
        //file 是个临时文件， 需要转存，否则本次请求结束后将被删除
        log.info(file.toString());


        String originalFileName = file.getOriginalFilename();

        assert originalFileName != null;
        //文件后缀
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        //使用UUID 生成文件名，防止文件同名覆盖
        String filenName = UUID.randomUUID().toString() + suffix;

        //判断basePath目录是否存在
        File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        try {
            //保存
            file.transferTo(new File(basePath + filenName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filenName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){ //参数名和前端保持一致
        try {
            //输入输出流
            FileInputStream inputStream = new FileInputStream(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();

            //设置相应类型
            response.setContentType("image/jpeg");

            //读写
            int len;
            byte[] buffer = new byte[1024];
            while((len = inputStream.read(buffer)) != -1){
                outputStream.write(buffer, 0, len);
                //刷新
                outputStream.flush();
            }

            //关闭资源
            inputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
